package exer;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author tongchen
 * @create 2023-04-05 16:27
 */
@WebServlet("/login")
public class Login extends HttpServlet {
    //使用dopost方法测试登录
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=utf-8");
        //获取两个变量
        String user=req.getParameter("user");
        String password=req.getParameter("password");
        System.out.println("测试账号密码....." +
                user+password);
        //判断账号密码的正确情况
        if("zhangsan".equals(user)&&"123456".equals(password)){
            //
            //登录成功，设置cookie并直接跳转
            HttpSession session = req.getSession(true);
            session.setAttribute("userInfo", user);
            //跳转
            resp.sendRedirect("index");
        }else{
            //错误直接将错误写回
            resp.getWriter().write("账号密码错误");
        }
    }
}
